package com.car.action.api;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.car.action.util.CommonController;
import com.car.common.model.Area;
import com.car.common.model.Tags;
import com.car.common.model.UserTags;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jfinal.plugin.activerecord.Db;
import com.utils.APIJSON;
import com.utils.DateUtil;
import com.utils.PicUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.Toolkit;

public class FindFriendController extends CommonController{
	
	public void clear() {
		List<UsersInfo> infos = UsersInfo.dao.find("select * from users_info where introduction is not null and length(introduction) > 0 and introduction like '%\\%%' order by id asc limit 4000 ");
		for(UsersInfo one : infos) {
			try {
				String introduction = StringUtil.decode(one.getIntroduction());
				Db.update("update users_info set introduction = '" + introduction +"' where id = "+ one.getId());
			} catch (Exception e) {
			}
		}
		List<Users> users = Users.dao.find("select * from users where nick_name is not null and length(nick_name) > 0 and nick_name like '%\\%%' order by id asc limit 4000");
		for(Users one : users) {
			System.out.println(one.getNickName());
			try {
				String nickname = StringUtil.decode(one.getNickName());
				Db.update("update users set nick_name = '" + nickname +"' where id = "+ one.getId());
			} catch (Exception e) {
			}
			
		}
		renderText("ok");
	}
/**  3个月 前  不登录用户 ，转成水号
 * UPDATE users as a , (SELECT id FROM users WHERE is_true = 1 AND login_status = 1 AND logout_time < 1546322083 ORDER BY RAND()  LIMIT 20000 ) as b
SET a.is_true = 2,
 a.is_show_nearby = 1 
WHERE
	a.id = b.id
	
	select count(id) from users where is_true = 1 and login_status =1 and logout_time < 1546322083 
 */
	/**
	 * 获取附近的人列表
	 */
	public void nearby_list() {
		String lat = "31.312204";
		if (!StringUtil.empty(getPara("lat"))) {
			lat = getPara("lat");
		} else {
			renderText(APIJSON.send(Lists.newArrayList()));
			return;
		}
		String lng = "120.604485";
		if (!StringUtil.empty(getPara("lng"))) {
			lng = getPara("lng");
		} else {
			renderText(APIJSON.send(Lists.newArrayList()));
			return;
		}
		String distance = "ROUND(6378.138 * 2 * ASIN(  SQRT(  POW(  SIN(  (  "
						   + lat + " * PI() / 180 - a.lat * PI() / 180 ) / 2  ),  2 ) + COS("
				           + lat + " * PI() / 180) * COS(a.lat * PI() / 180) * POW( SIN( ( " 
	                       + lng + " * PI() / 180 - a.lng * PI() / 180 ) / 2 ), 2 ))) * 1000) ";
		
		String sql = "select a.user_id," + distance + " as distance,u.login_status,logout_time,u.is_true ";
		
		String andSql = " from users u left join users_info as a  on u.id = a.user_id ";
		
		andSql += " where a.lat is not null and a.lng is not null and u.is_show_nearby = 1 and u.nick_name is not null and u.status = 1 ";
		andSql += " and u.user_header is not null and LENGTH(u.user_header) > 0 and u.disable_time != -1 and u.disable_time < " + SystemClock.now() /1000;
		if (!StringUtil.empty(getPara("sex"))) {
			andSql += " and u.sex = " + getPara("sex");
		}
		if (!StringUtil.empty(getPara("area_id"))) {
			andSql += " and u.area_id = " + getPara("area_id");
        }
		if (!StringUtil.empty(getPara("minage"))) {
			andSql += " and u.birthday < " +(SystemClock.now()/1000L - getParaToInt("minage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("maxage"))) {
			andSql += " and u.birthday > " +(SystemClock.now()/1000L - getParaToInt("maxage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("time"))) {
			andSql += " and (u.login_status = 0 or (u.login_status = 1 and u.logout_time >"+ (SystemClock.now()/1000L - 3 * 24*60* 60) +" )) ";
        } else {
        	andSql += " and (u.login_status = 0 or (u.login_status = 1 and u.logout_time >"+ (SystemClock.now()/1000L - 7 * 24*60* 60) +" )) ";
        }
		int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        }
        
        andSql += " order by distance limit " + (page-1)*15 + ",15";
        Long user_id = super.getUserId();
        if (user_id.intValue() > 0) {
        	Users users = Users.dao.findById(user_id);
        	if (users.getAreaId() == null ) {
        		String sheng = Toolkit.getAdd(lat + ","+ lng);
            	if (sheng != null) {
            		Area area = Area.dao.findFirst("select code from area where name like '%"+sheng+"%'");
            		if (area != null) {
            			Db.update("update users set area_id = " + area.getCode() + " where id = " + user_id);
            		}
            	}
        	}
        	Db.update("update users_info set lat = '" + lat +"' ,lng = '"+ lng+"' where user_id = " + user_id);
        }
        List<UsersInfo> infoList = UsersInfo.dao.find(sql + andSql);
        ArrayList<Map<String,Object>> result = Lists.newArrayList();
        for(UsersInfo info :infoList) {
        	Map<String,Object> temp = Maps.newHashMap();
        	String sql1 = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
			sql1 += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit from users as u left join area ae on ae.code = u.area_id where u.id = " + info.get("user_id");
			Users user = Users.dao.findFirst(sql1);
			if (user == null) {
				temp.put("user_data", Lists.newArrayList());
			} else {
				temp.put("user_data", Users.dao.info(user,"card_list"));
			}
			int login_status = info.getInt("login_status");
			if (login_status == 0) {
				temp.put("time_desc",   "当前在线");
				temp.put("time_status", 1);
			} else {
				temp.put("time_desc",   DateUtil.cul(info.getLong("logout_time")));
				temp.put("time_status", 2);
			}
			temp.put("distance", Toolkit.distance_name(info.getInt("distance")) );
			result.add(temp);
        }
        renderText(APIJSON.send(result));
	}
	
	/**
	 * 推荐墙
	 */
	public void discover_list() {
		String sql = "select u.id,u.login_status,u.logout_time,u.tag_ids,u.private_tag_ids ";
		Long user_id = super.getUserId();
		String andSql = " from users as u left join users_info ui on ui.user_id = u.id ";
		
		andSql += " where u.is_show_hot = 1 and u.nick_name is not null and LENGTH(u.nick_name) > 0 and u.status = 1 and u.id != " + user_id;
		// and u.disable_time < + SystemClock.now() /1000
		andSql += " and u.user_header is not null and LENGTH(u.user_header) > 0 and u.disable_time != -1 " ;
		if (!StringUtil.empty(getPara("sex"))) {
			andSql += " and u.sex = " + getPara("sex");
		}
		if (!StringUtil.empty(getPara("area_id"))) {
			andSql += " and u.area_id = " + getPara("area_id");
        }
		if (!StringUtil.empty(getPara("orientation"))) {
			andSql += " and ui.orientation = " + getPara("orientation");
        }
		if (!StringUtil.empty(getPara("emotion"))) {
			andSql += " and ui.emotion = " + getPara("emotion");
        }
		if (!StringUtil.empty(getPara("minage"))) {
			andSql += " and u.birthday < " +(SystemClock.now()/1000L - getParaToInt("minage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("maxage"))) {
			andSql += " and u.birthday > " +(SystemClock.now()/1000L - getParaToInt("maxage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("login_time"))) {
			andSql += " and (u.login_status = 0 or u.logout_time >"+ (SystemClock.now() - 3 * 24*60* 60) +" )";
        } 
		int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        }
        
        if(user_id > 0L) {
        	List<UserTags> usertagsList = UserTags.dao.find("select tag_id from user_tags where user_id = " + user_id);
        	if(usertagsList != null && usertagsList.size() >0){
        		Set<Integer> matchTags = Sets.newHashSet();
        		for(UserTags one : usertagsList) {
        			Tags tags = Tags.dao.findById(one.getInt("tag_id"));
        			if (tags != null) {
        				String matching = tags.getStr("matching");
            			if(!StringUtil.empty(matching)) {
            				String[] nameArray = matching.split(",");
            				for(String id:nameArray){
            					if (!matchTags.contains(id)){
            						matchTags.add(Integer.valueOf(id));
            					}
            				}
            			}
        			}
        			
        		}
        		if (matchTags.size() > 0){
        			StringBuffer likeSql = new StringBuffer(" and (");
            		int i = 0;
                	for(Integer one : matchTags) {
                		if (i ==0) {
                			
                		} else {
                			likeSql.append(" or ") ;
                		}
                		likeSql.append(" tag_ids  like '%") ;
                		likeSql.append(one) ;
                		likeSql.append("," ) ;
                		likeSql.append("%'" )   ;
                	
                		i++;
                	}
                	likeSql.append(" ) ") ;
                	andSql += likeSql.toString();
        		}
        	
        	}
        	
        }
        andSql += " order by  u.login_status, u.is_true asc, u.vip_end_time desc,u.hot_val desc  limit " + (page-1)*15 + ",15";
        List<Users> infoList = Users.dao.find(sql + andSql);
        ArrayList<Map<String,Object>> result = Lists.newArrayList();
        /*
        if(user_id > 0L && page == 1) {
        	Users users = Users.dao.findById(user_id);
        	if (users != null && users.getVipEndTime() < SystemClock.now() /1000L ) {
        		Map<String,Object> temp = Maps.newHashMap();
            	String sql1 = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
    			sql1 += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + user_id;
    			Users user = Users.dao.findFirst(sql1);
    			if (user == null) {
    				temp.put("user_data", Lists.newArrayList());
    			} else {
    				temp.put("user_data", Users.dao.info(user));
    			}
    			temp.put("is_me", 1);
    			result.add(temp);
        	}
        }
        */
        for(Users info :infoList) {
        	Map<String,Object> temp = Maps.newHashMap();
        	String sql1 = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
			sql1 += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + info.getId();
			Users user = Users.dao.findFirst(sql1);
			if (user == null) {
				temp.put("user_data", Lists.newArrayList());
			} else {
				temp.put("user_data", Users.dao.info(user,"card_list"));
			}
			temp.put("is_me", 2);
			int login_status = info.getInt("login_status");
			if (login_status == 0) {
				temp.put("time_desc",   "当前在线");
				temp.put("time_status", 1);
			} else {
				System.out.println("logout_time" + info.get("logout_time"));
				temp.put("time_desc",   DateUtil.cul(info.getLong("logout_time")));
				//temp.put("time_desc",   DateUtil.cul(Long.valueOf(String.valueOf(info.get("logout_time")))));
				temp.put("time_status", 2);
			}
			result.add(temp);
        }
        renderText(APIJSON.send(result));
	}
	
	
	/**
	 * 热门推荐
	 */
	public void hot_list() {
		List<Users> usersList = Users.dao.find("select id ,nick_name,user_header from users where nick_name is not null and length(nick_name) > 0 and user_header is not null and length(user_header) > 0 and  vip_end_time > 0 and login_status = 0  order by id desc limit 10 ");
		ArrayList<Map<String,Object>> result = Lists.newArrayList();
		for(Users users :usersList) {
        	Map<String,Object> temp = Maps.newHashMap();
        	temp.put("id", users.get("id"));
        	temp.put("nick_name",   users.get("nick_name"));
        	temp.put("user_header", PicUtil.QINIU_DIR + users.get("user_header"));
        	
        	result.add(temp);
		}
		renderText(APIJSON.send(result));
	}
	
}
